//
//  WFCUFUserCircleVC.m
//  WFChatUIKit
//
//  Created by 陈*敏 on 2/6/2024.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUFUserCircleVC.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"
#import "WFCUImage.h"

#import "AFNetworking.h"
#import <WFChatClient/WFCChatClient.h>
#import "SHFriendHeadView.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "Moment.h"
#import "Comment.h"
#import <Photos/Photos.h>

@interface WFCUFUserCircleVC ()<UITableViewDataSource, UITableViewDelegate ,SHFriendHeadViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;
 

 
@property (nonatomic,strong) SHFriendHeadView *tableHeadView;
//@property (nonatomic,strong) UIImageView *coverImageView;
//@property (nonatomic,strong) UIImageView *headImageView;

@property (nonatomic,strong) WFCCUserInfo *me;



@property (nonatomic,strong) UIView *barBackgroundView;
@property (nonatomic, strong)id obj;


@end

@implementation WFCUFUserCircleVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

//    self.navigationController.navigationBar.hidden = YES;
    NSMutableArray *barSubviews = [NSMutableArray array];
    //将导航栏的子控件添加到数组当中,取首个子控件设置透明度(防止导航栏上存在非导航栏自带的控件)
    for (UIView * view in self.navigationController.navigationBar.subviews) {
        if(![view isMemberOfClass:[UIView class]]){
            [barSubviews addObject:view];
        }
    }
    if (!self.barBackgroundView) {
         
        UIView *barBackgroundView = [barSubviews firstObject];
        barBackgroundView.alpha   = 0.;
        self.barBackgroundView = barBackgroundView;
    }
 
//    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(onBackBtn:)];
//    self.navigationController.navigationItem.backBarButtonItem = back;
    [self.navigationController.navigationItem.backBarButtonItem setImage:[WFCUImage imageNamed:@"back_white"]];
    
    UIBarButtonItem *barck = self.navigationController.navigationItem.backBarButtonItem;
    [barck setImage:[UIImage imageNamed:@"back_white"]] ;
    NSLog(@"barck %@ ",barck ) ;
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

 
    self.barBackgroundView.alpha   = 1.;
 
    
}
#pragma mark - UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
 
    if (scrollView.contentOffset.y > ZmNavigationHeight_N() + 20){
        self.barBackgroundView.alpha   = 1.;

    }else{
        self.barBackgroundView.alpha   = 0.;

    }
    
    [self.view endEditing:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
 
    
  
    //    back_white
    
    self.view.backgroundColor = [UIColor whiteColor];

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor = [UIColor clearColor];
    if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = self.tableHeadView;
    [self.view addSubview:self.tableView];

    
    self.dataArray = @[].mutableCopy;
 
    self.me = [[WFCCIMService sharedWFCIMService] getUserInfo:self.userId refresh:NO];

 
  

    [self netWord];

  
    

}
 

- (void)netWord{
    
    WEAKSELF_ZM
    
    [self.tableHeadView.avatarImageView sd_setImageWithURL:[NSURL URLWithString:self.me.portrait] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        NSLog(@"%@ err%@",image,error);
    }];
    self.tableHeadView.userName = self.me.displayName;
    
    
    
    NSString *savedToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = self.userId ;/// [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
 
    [manager.requestSerializer setValue:savedToken forHTTPHeaderField:@"authToken"];

    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/userTopic/%@" , userId];
//    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/friend-circle/topic/topicList" ];

    
    [manager GET:url parameters:@{@"userId":userId} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            
//            NSLog(@" ret---  %@ ", dic );
            weakSelf.obj = dic;
            
            [weakSelf loadDatas];
            
        }

 
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error) {
             
            NSLog(@" ret---  %@ ", error );

        }
 
    }];
    
    
}

- (void)loadDatas{
    
    
    WEAKSELF_ZM
    
    NSArray *rows = @[];

    if (weakSelf.obj) {
        rows  = [weakSelf.obj handleNullObjectForKey:@"rows"];
    }
    
    NSLog(@" ret---  %@ ", rows );
    
 
    NSMutableArray * tempArray = [NSMutableArray array];

    for (int i = 0; i<rows.count; i++) {

        NSDictionary *obj1 = rows[i];
        NSDictionary *obj2 = [obj1 handleNullObjectForKey:@"topic"];
//                NSDictionary *obj3 = [NSObject dictionaryWithJsonString:[obj2 handleNullObjectForKey:@"content"]];

        Moment *moment = [[Moment alloc] init];
//                moment.commentList = commentList;
//                moment.praiseNameList = @"胡一菲，唐悠悠，陈美嘉，吕小布，曾小贤，张伟，关谷神奇";
        
        NSArray *likeList = [obj1 handleNullObjectForKey:@"likeList"];
        NSMutableArray * praiseNameList = [NSMutableArray array];

        for (int i = 0; i<likeList.count; i++) {
            
            NSDictionary *praise = likeList[i];

            [praiseNameList addObject:[praise handleNullObjectForKey:@"displayName"]];
            
        }
        moment.praiseNameList = [praiseNameList componentsJoinedByString:@","];
        moment.isLike = [[obj1 handleNullObjectForKey:@"like"] containsString:@"Y"];
        
        NSArray *replyList = [obj1 handleNullObjectForKey:@"replyList"];
        NSMutableArray * commentList = [NSMutableArray array];
        for (int j = 0; j < replyList.count; j ++) {
            NSDictionary *reply = replyList[j];

            Comment *comment = [[Comment alloc] init];
            comment.userName = [reply handleNullObjectForKey:@"displayName"];
            comment.text = [reply handleNullObjectForKey:@"content"];
            comment.time = [NSObject retWithLongDate:[reply handleNullObjectForKey:@"createTime"]];
            comment.pk = 0;
            comment.replyId = [reply handleNullObjectForKey:@"replyId"];
            [commentList addObject:comment];
        }
        
        
        moment.commentList = commentList;
        moment.userName = [obj2 handleNullObjectForKey:@"nickName"] ;
        moment.time = [NSObject retWithLongDate:[obj2 handleNullObjectForKey:@"createTime"]];
        moment.createTime = [obj2 handleNullObjectForKey:@"createTime"] ;

        
        
        moment.singleWidth = 500;
        moment.singleHeight = 315;
        moment.userThumbPath = [obj2 handleNullObjectForKey:@"portrait"] ;
        moment.topicId = [obj2 handleNullObjectForKey:@"topicId"] ;
        moment.text = [obj2 handleNullObjectForKey:@"content"];
        moment.topicType = [obj2 handleNullObjectForKey:@"topicType"] ;

        moment.isDelete = ![weakSelf.me.userId containsString:[obj2 handleNullObjectForKey:@"userId"]];
        
        
        NSString *imageStr = [NSString stringWithFormat:@"%@",[obj2 handleNullObjectForKey:@"location"]];
        if (imageStr.length > 1 && [[obj2 handleNullObjectForKey:@"topicType"] containsString:@"IMAGE"] ) {
             
            moment.imageFArr = [[obj2 handleNullObjectForKey:@"location"] componentsSeparatedByString:@","].mutableCopy  ;
            moment.fileCount = moment.imageFArr.count;

            [tempArray addObject:moment];

        }
       
        
    }
    weakSelf.dataArray = tempArray ;
    
    [weakSelf.tableView reloadData];

        
}
 


#pragma mark - Getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];

//        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -(44 + kStatusBarH), kWidth, kHeight) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = self.tableHeadView;
    }
    return _tableView;
}

- (SHFriendHeadView *)tableHeadView
{
    if (!_tableHeadView) {
        
        CGFloat wsf =  ZmScreenWidth_N()   ;
        CGFloat ws1 = wsf  / 360 * 282;
        
        _tableHeadView = [[SHFriendHeadView alloc] initWithFrame:CGRectMake(0, 0, kWidth, ws1)];
        _tableHeadView.backgroundColor = [UIColor whiteColor];
        _tableHeadView.userInteractionEnabled = YES;
//        [_tableHeadView addSubview:self.coverImageView];
//        [_tableHeadView addSubview:self.headImageView];
        _tableHeadView.userName = self.me.displayName;
//        _tableHeadView.userAvatar = [self.me.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        _tableHeadView.backgroundUrl = [NSString stringWithFormat:@"%@",@"circle_head1"];
         
        
        _tableHeadView.delegate = self;
    }
    return _tableHeadView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
   

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    [cell.contentView removeAllSubviews];
    
    
    Moment *moment  = self.dataArray[indexPath.section];
    
//    NSDictionary *obj3 = [NSObject dictionaryWithJsonString:[dic handleNullObjectForKey:@"topicContent"]];

    WEAKSELF_ZM
//    UIImageView * portraitView = [[UIImageView alloc] init ];
// 
//    [portraitView sd_setImageWithURL:[NSURL URLWithString:[moment.userThumbPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"]];
//    
//    [cell.contentView addSubview:portraitView];
//    portraitView.sd_layout.centerYEqualToView(cell.contentView).leftSpaceToView(cell.contentView, 15).widthIs(38).heightIs(38);
//    portraitView.sh_chain_extend.roundSize(10).modeFill();

    // 日期格式字符串  2016-05-17 15:07:54
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    [fmt setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];//默认时区为当前系统时区比如东8
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *created_at = [fmt dateFromString:moment.createTime];
    fmt.dateFormat = @"MM";
   NSString *m = [fmt stringFromDate:created_at];

    fmt.dateFormat = @"dd";
   NSString *d = [fmt stringFromDate:created_at];
    
    UILabel *titleL = [[UILabel alloc] init ];
    [cell.contentView addSubview:titleL];

    titleL.sd_layout.leftSpaceToView(cell.contentView, 15).centerYEqualToView(cell.contentView ).autoHeightRatio(0);
    [titleL setSingleLineAutoResizeWithMaxWidth:200];
    titleL.sh_chain_extend.font_size(24).titleColor([UIColor colorWithHexExtendString:@"#1D1D1D"]).title([NSString stringWithFormat:@"%@",d]);

    
    
    UILabel *titleL1 = [[UILabel alloc] init ];
    [cell.contentView addSubview:titleL1];

    titleL1.sd_layout.leftSpaceToView(titleL, 2).bottomEqualToView(titleL).autoHeightRatio(0);
    [titleL1 setSingleLineAutoResizeWithMaxWidth:200];
    titleL1.sh_chain_extend.font_size(14).titleColor([UIColor colorWithHexExtendString:@"#1D1D1D"]).title([[NSString stringWithFormat:@"%d",[m intValue]] stringByAppendingString:@"月"]);

    
    
    
    UIImageView * collView = [[UIImageView alloc] init ];
    [cell.contentView addSubview:collView];
    collView.sd_layout.centerYEqualToView(titleL).leftSpaceToView(titleL1, 12).widthIs(88).heightIs(88);
    
    NSInteger select = 1;
    CGFloat height = 88;
    if (moment.imageFArr.count == 1) {
        select = 1;
    } else  if (moment.imageFArr.count <5){
        select = 2;
        height = 43;
    }else  {
        select = 3;
        height = 28;

    }
    NSMutableArray *list = [NSMutableArray array];
 
    for (int i = 0; i < moment.imageFArr.count; i++) {
         
        
        UIImageView *btn3 = [[UIImageView alloc]init];
        
        [collView addSubview:btn3];
        btn3.sh_chain_extend.modeFill().clipsToBounds(YES).roundSize(4).addTarget_action(self, @selector(clickImage:));
        btn3.sd_layout.heightIs(height);
 
        [btn3 sd_setImageWithURL:[NSURL URLWithString:[moment.imageFArr[i] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]  ];
        
        [list addObject:btn3];
        
    }
    
    [collView setupAutoWidthFlowItems:list withPerRowItemsCount:select verticalMargin:10 horizontalMargin:10 verticalEdgeInset:0 horizontalEdgeInset:0];

    
    
    UILabel *timeL = [[UILabel alloc] init ];
    [cell.contentView addSubview:timeL];

    timeL.sd_layout.leftSpaceToView(collView, 12).topEqualToView(collView).autoHeightRatio(0);
    [timeL setSingleLineAutoResizeWithMaxWidth:200];
    timeL.sh_chain_extend.font_size(14).titleColor([UIColor colorWithHexExtendString:@"#1D1D1D"]).title(moment.text);

     
    
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;

}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}
// 设置section FooterView 的背景色
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}
// 设置section HeaderView 的背景色
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}

- (void)clickImage:(UIButton *)btn{
    
    
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
